import { reactive, ref, shallowReactive, provide } from 'vue'
import usePermissionStore from '@/store/modules/permission'
import { doAsyncRoutes } from '@/setting'
import { isValid } from '@/utils'
import usePrice from '@/hooks/usePrice'

export const useTableHeight = async function (currentIns: any): Promise<number> {
  return new Promise((resolve) => {
    const clientHeight = document.querySelector('.main-body')?.getBoundingClientRect().height || 0
    const tableHeaderHeight = document.querySelector('.arco-table-header')?.getBoundingClientRect().height || 41
    if (currentIns) {
      let tempHeight = tableHeaderHeight
      if (currentIns.refs.tableHeaderRef) {
        const header = (currentIns.refs as any).tableHeaderRef.$el
        tempHeight += header.clientHeight
      }
      if (currentIns.refs.tableFooterRef) {
        const footer = (currentIns.refs as any).tableFooterRef.$el
        tempHeight += footer.clientHeight
      }
      resolve(clientHeight - tempHeight - 58)
    }
    resolve(150)
  })
}

export const useRowKey = function (propName: string) {
  return propName
}

export const useRowSelection = function () {
  const type = ref('checkbox')
  const showCheckedAll = ref(true)
  const selectedRowKeys = ref<Array<string>>([])
  const onSelectionChange = (tempSelectRows: Array<string>) => {
    selectedRowKeys.value = tempSelectRows
  }
  return {
    type,
    showCheckedAll,
    selectedRowKeys,
    onSelectionChange,
  }
}

export const useTableColumn = function (columns: []) {
  return columns.map((it: any) => {
    const _option = {
      align: 'left',
      ...it,
    }
    // 存在 unit 情况下 title 增加(单位)
    // 移除补充2位小数逻辑
    if (_option.unit) {
      Object.assign(_option, {
        title: it.title + `(${it.unit})`,
      })
    }
    // 设置了 ellipsis，补 tooltip 字段
    if (_option.ellipsis) {
      Object.assign(_option, {
        tooltip: it.hasOwnProperty('tooltip') ? it.tooltip : true,
      })
    }
    return _option
  })
}

export const usePagination = function () {
  const paginationInfo = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageCount: 1,
    pageSizes: [10, 20, 50],
    setTotalSize(totalSize: number) {
      paginationInfo.pageCount = totalSize
    },
  })
  return paginationInfo
}

export const useTableOperates = function (operates: []) {
  if (operates) {
    const { resourcePermission } = usePermissionStore()
    return operates.map((it: any) => {
      let _flag = true
      const permission = it.permission
      // 存在 permission 并且 关闭异步路由不控制按钮权限
      if (permission && doAsyncRoutes) {
        _flag = resourcePermission.includes(permission)
      }
      return {
        ...it,
        permission: { flag: _flag },
      }
    })
  } else {
    return null
  }
}

export const useTableButtons = function (buttons: []) {
  if (buttons) {
    const { resourcePermission } = usePermissionStore()
    return buttons.map((it: any) => {
      let _flag = true
      const permission = it.permission
      // 存在 permission 并且 关闭异步路由不控制按钮权限
      if (permission && doAsyncRoutes) {
        _flag = resourcePermission.includes(permission)
      }
      return {
        ...it,
        permission: { flag: _flag },
      }
    })
  } else {
    return null
  }
}

export const useFetchTableDataApi = function (table: any, queryParam: any, api: any) {
  tableQueryParam.value = queryParam
  return (pageNumber?: Number) => {
    return new Promise((resolve) => {
      const param = {
        pageNumber: table?.pagination?.page,
        pageSize: table?.pagination?.pageSize,
        ...queryParam,
      }
      if (isNaN(pageNumber) == false) {
        param.pageNumber = pageNumber
        table.pagination.page = pageNumber
      }
      // 防止pageNumber==undefined; 分页器auto-adjust属性影响
      if (!param.pageNumber) {
        param.pageNumber = 1
        table.pagination.page = 1
      }

      table.tableLoading = true
      api(param).then((res: any) => {
        const result = res.result
        const { data, total } = result
        table.tableLoading = false
        table.dataList = data
        table.pagination.setTotalSize(total)
        rowSelectableHandle(table)

        resolve(result)
      })
    })
  }
}

export const useFetchTableDataApiNoPage = function (table: any, queryParam: any, api: any) {
  tableQueryParam.value = queryParam
  return () => {
    return new Promise((resolve) => {
      const param = {
        ...queryParam,
      }
      table.tableLoading = true
      api(param).then((res: any) => {
        const result = res.result
        const newresult = result ? arrayhandle(result) : result
        const datas = newresult
        console.log(datas)
        table.tableLoading = false
        table.dataList = datas
        // table.pagination.setTotalSize(datas.length)
        rowSelectableHandle(table)

        resolve(result)
      })
    })
  }
}

// 处理表格数据是否可勾选
const rowSelectableHandle = (table: any) => {
  // 获取表格的行选择配置
  const rowSelection = table.rowSelection
  // 如果行选择配置存在
  if (rowSelection) {
    // 获取是否显示勾选的配置项
    const showChecked = rowSelection.showChecked
    // 如果显示勾选的配置项存在且为函数
    if (showChecked && typeof showChecked == 'function') {
      // 遍历数据列表，为每个数据项设置禁用状态
      table.dataList.forEach((dataItem: any) => {
        // 根据showChecked函数的返回值设置数据项的禁用状态
        dataItem.disabled = !showChecked(dataItem)
      })
    }
  }
}

const arrayhandle = (result: any[]) => {
  result.map((item) => {
    item.children = item.resourceEntityList
    if (item.children && item.children.length) {
      item.show = false
      arrayhandle(item.children)
    } else {
      if (item.saasDictList && item.saasDictList.length) {
        item.show = false
        item.saasDictList.map((ele: { show: boolean }) => {
          ele.show = true
        })
        item.children = item.saasDictList
      }
    }
  })
  return result
}

const tableQueryParam = { value: {} }
export const useTable = function (options: any) {
  const dataList = shallowReactive([]) as Array<any>
  // const dataList = shallowRef<Array<any>>([])
  const tableHeaderRef = ref(null)
  const tableFooterRef = ref(null)
  const tableHeight = ref(0)
  const bordered = ref(false)
  const striped = ref(false)
  const tableLoading = ref(true)
  const pagination = usePagination()
  provide('table-border', bordered)
  provide('table-dataList', dataList)
  provide('table-queryParam', options.queryParam || tableQueryParam)
  // provide('table-dataList', dataList.value)

  return reactive({
    dataList,
    tableHeaderRef,
    tableFooterRef,
    tableHeight,
    bordered,
    striped,
    tableLoading,
    pagination,
    ...options,
    columns: useTableColumn(options?.columns),
    operates: useTableOperates(options?.operates),
    buttons: useTableButtons(options?.buttons),
  })
}
